<template>
    <div class="p-2">
        <el-card shadow="never">
            <template #header>
                <div class="card-header">
                    <span>{{ pageTitle }}</span>
                    <el-button @click="goBack" link>返回列表</el-button>
                </div>
            </template>

            <el-form ref="questionsFormRef" :model="form" :rules="rules" label-width="120px">
                <!-- 基本信息 -->
                <el-divider content-position="left">基本信息</el-divider>
                <el-form-item label="内容" prop="title">
                    <div class="content-list-container">
                        <div v-for="(item, index) in titleList" :key="index" class="content-item">
                            <el-row :gutter="10" class="mb-2">
                                <el-col :span="18">
                                    <template v-if="item.type === 'text'">
                                        <el-input v-model="item.content" type="textarea" :rows="2" placeholder="请输入文本内容" @input="handleContentChange" />
                                    </template>
                                    <template v-else-if="item.type === 'image'">
                                        <!-- <div class="image-preview">
                                            <img v-if="item.content" :src="item.content" class="preview-image" />
                                            <span v-else class="no-image">暂无图片</span>
                                        </div> -->
                                        <ImageUpload
                                            :ref="(el) => setImageUploadRef(el, index)"
                                            v-model="item.ossIds"
                                            :limit="1"
                                            :file-size="5"
                                            @update:modelValue="handleImageUpdate(index, $event)"
                                        />
                                    </template>
                                </el-col>
                                <el-col :span="6" class="content-item-actions">
                                    <el-button type="primary" @click="moveItem(index, 'up')" :disabled="index === 0">
                                        <el-icon><ArrowUp /></el-icon>
                                    </el-button>
                                    <el-button type="primary" @click="moveItem(index, 'down')" :disabled="index === titleList.length - 1">
                                        <el-icon><ArrowDown /></el-icon>
                                    </el-button>
                                    <el-button type="danger" @click="removeContentItem(index)" :disabled="titleList.length <= 1">
                                        <el-icon><Delete /></el-icon>
                                    </el-button>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="content-actions mt-2">
                            <el-button type="primary" @click="addContentItem('text')">
                                <el-icon><Document /></el-icon> 添加文本
                            </el-button>
                            <el-button type="success" @click="addContentItem('image')">
                                <el-icon><Picture /></el-icon> 添加图片
                            </el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="类型" prop="questionType">
                    <!-- <el-select v-model="form.questionType" placeholder="请选择题目类型" @change="handleTypeChange">
            <el-option label="单选题" value="single_choice" />
            <el-option label="多选题" value="multiple_choice" />
            <el-option label="填空题" value="fill_blank" />
            <el-option label="判断题" value="true_false" />
          </el-select> -->

                    <el-radio-group v-model="form.questionType" @change="handleTypeChange">
                        <el-radio v-for="dict in ai_answer_topic_type" :key="dict.value" :value="dict.value">{{
                            dict.label
                            }}</el-radio>
                    </el-radio-group>

                </el-form-item>
                <el-form-item label="等级" prop="difficulty">
                    <el-rate v-model="form.difficulty" :max="5" :texts="['简单', '较简单', '中等', '较难', '困难']" show-text />
                </el-form-item>
                <el-form-item label="分类" prop="category">
                    <el-input v-model="form.category" placeholder="请输入题目分类/标签" />
                </el-form-item>
                <el-form-item label="分值" prop="score">
                    <el-input-number v-model="form.score" :min="0" :max="100" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 单选项区域 -->
                <template v-if="form.questionType === 'single_choice'">
                    <el-divider content-position="left">选项设置</el-divider>
                    <div v-for="(option, index) in options" :key="index" class="option-item">
                        <el-row :gutter="10" class="mb-2">
                            <el-col :span="2" class="option-label">
                                <span class="label-text">{{ option.label }}</span>
                            </el-col>
                            <el-col :span="16">
                                <el-input v-model="option.optionContent" :placeholder="`请输入选项${index + 1}内容`" />
                            </el-col>
                            <el-col :span="3">
                                <el-radio 
                                    v-model="singleCorrectAnswer" 
                                    :label="index"
                                    @change="handleSingleAnswerChange(index)"
                                >正确答案</el-radio>
                            </el-col>
                            <el-col :span="3">
                                <el-button type="danger" @click="removeOption(index)"
                                    :disabled="options.length <= 2">删除</el-button>
                            </el-col>
                        </el-row>
                    </div>
                    <el-button type="primary" @click="addOption" class="mt-2">添加选项</el-button>
                </template>

                <!-- 多选项区域 -->
                <template v-if="form.questionType === 'multiple_choice'">
                    <el-divider content-position="left">选项设置</el-divider>
                    <div v-for="(option, index) in options" :key="index" class="option-item">
                        <el-row :gutter="10" class="mb-2">
                            <el-col :span="2" class="option-label">
                                <span class="label-text">{{ option.label }}</span>
                            </el-col>
                            <el-col :span="16">
                                <el-input v-model="option.optionContent" :placeholder="`请输入选项${index + 1}内容`" />
                            </el-col>
                            <el-col :span="3">
                                <el-checkbox v-model="option.isCorrect" label="正确答案" />
                            </el-col>
                            <el-col :span="3">
                                <el-button type="danger" @click="removeOption(index)"
                                    :disabled="options.length <= 2">删除</el-button>
                            </el-col>
                        </el-row>
                    </div>
                    <el-button type="primary" @click="addOption" class="mt-2">添加选项</el-button>
                </template>

                <!-- 填空题答案 -->
                <template v-if="form.questionType === 'fill_blank'">
                    <el-divider content-position="left">答案设置</el-divider>
                    <el-form-item label="正确答案">
                        <el-input v-model="fillBlankAnswer" type="textarea" :rows="2" placeholder="请输入填空题答案" />
                    </el-form-item>
                </template>

                <!-- 判断题答案 -->
                <template v-if="form.questionType === 'true_false'">
                    <el-divider content-position="left">答案设置</el-divider>
                    <el-form-item label="正确答案">
                        <el-radio-group v-model="trueFalseAnswer">
                            <el-radio :label="true">正确</el-radio>
                            <el-radio :label="false">错误</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>

                <!-- 题目解析 -->
                <el-divider content-position="left">题目解析</el-divider>
                <el-form-item label="题目解析" prop="explanation">
                    <el-input v-model="form.explanation" type="textarea" :rows="3" placeholder="请输入题目解析" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="buttonLoading">保存</el-button>
                    <el-button @click="goBack">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup name="AddQuestions" lang="ts">
import { addQuestions, getQuestions, updateQuestions, contentType } from '@/api/answer/questions';
import { QuestionsForm } from '@/api/answer/questions/types';
import { OptionsForm, OptionsQuery } from '@/api/answer/options/types';
import { useRouter, useRoute } from 'vue-router';
import ImageUpload from '@/components/ImageUpload/index.vue';
import { ArrowUp, ArrowDown, Delete, Document, Picture } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { ai_answer_topic_type } = toRefs<any>(proxy?.useDict('ai_answer_topic_type', 'ai_answer_topic_level', 'ai_answer_topic_status'));

// 页面标题
const pageTitle = ref('添加题目');

const buttonLoading = ref(false);
const questionsFormRef = ref<ElFormInstance>();
const imageUploadRefs = ref<any[]>([]);

// 设置ImageUpload组件引用
const setImageUploadRef = (el: any, index: number) => {
    if (el) {
        imageUploadRefs.value[index] = el;
    }
};

// 表单数据初始化
const initFormData: QuestionsForm = {
    questionId: undefined,
    title: undefined,
    questionType: 'single_choice',
    difficulty: 3, // 默认中等难度
    category: undefined,
    status: 1, // 默认启用
    score: 10, // 默认分值
    explanation: undefined,
    answer: undefined,
};

const form = ref<QuestionsForm>({ ...initFormData });

// 内容列表初始化
const titleList : contentType[] = ref([
    {
        content: '',
        type: 'text'
    }
]);

// 添加内容项（文本或图片）
const addContentItem = (type: 'text' | 'image') => {
    titleList.value.push({
        content: '',
        ossIds: '',
        type: type
    });
};

// 删除内容项
const removeContentItem = (index: number) => {
    if (titleList.value.length > 1) {
        titleList.value.splice(index, 1);
    }
};

// 移动内容项
const moveItem = (index: number, direction: 'up' | 'down') => {
    if (direction === 'up' && index > 0) {
        const temp = titleList.value[index];
        titleList.value[index] = titleList.value[index - 1];
        titleList.value[index - 1] = temp;
    } else if (direction === 'down' && index < titleList.value.length - 1) {
        const temp = titleList.value[index];
        titleList.value[index] = titleList.value[index + 1];
        titleList.value[index + 1] = temp;
    }
};

// 处理图片更新
const handleImageUpdate = (index: number, value: string) => {
    // 获取ImageUpload组件的引用
    const imageUploadRef = imageUploadRefs.value[index];
    if (imageUploadRef) {
        // 使用ossId作为图片内容
        const imageUrls = imageUploadRef.getImageUrls();
        titleList.value[index].content = imageUrls && imageUrls.join(',');
    }
    // titleList.value[index].ossIds = value;

    // 触发表单验证
    nextTick(() => {
        questionsFormRef.value?.validateField('title');
    });
};

// 处理内容变化
const handleContentChange = () => {
    // 触发表单验证
    nextTick(() => {
        questionsFormRef.value?.validateField('title');
    });
};

// 将内容列表转换为JSON字符串
const convertTitleListToJson = () => {
    return JSON.stringify(titleList.value);
};

// 将JSON字符串解析为内容列表
const parseJsonToTitleList = (jsonStr: string) => {
    try {
        const parsed = JSON.parse(jsonStr);
        if (Array.isArray(parsed) && parsed.length > 0) {
            titleList.value = parsed;
        } else {
            // 如果解析结果不是数组或为空，则创建一个默认文本项
            titleList.value = [{ content: jsonStr || '', type: 'text' }];
        }
    } catch (error) {
        // 如果解析失败，将原始字符串作为文本内容
        titleList.value = [{ content: jsonStr || '', type: 'text' }];
    }
};

// 自定义验证器：验证题目内容
const validateTitle = (rule: any, value: any, callback: any) => {
    // 检查titleList是否有有效内容
    const hasValidContent = titleList.value.some(item => {
        if (item.type === 'text') {
            return item.content && item.content.trim() !== '';
        } else if (item.type === 'image') {
            return item.content && item.content !== '';
        }
        return false;
    });
    
    if (!hasValidContent) {
        callback(new Error('题目内容不能为空'));
    } else {
        callback();
    }
};

// 表单验证规则
const rules = {
    title: [{ validator: validateTitle, trigger: 'blur' }],
    questionType: [
        { required: true, message: '题目类型不能为空', trigger: 'change' }
    ],
    difficulty: [{ required: true, message: '难度等级不能为空', trigger: 'blur' }],
    category: [{ required: true, message: '题目分类/标签不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    score: [{ required: true, message: '题目分值不能为空', trigger: 'blur' }],
    explanation: [{ required: true, message: '题目解析不能为空', trigger: 'blur' }]
};

// 表单数据初始化
const initOptions = () => {
    return [
        {
            optionContent: '',
            optionOrder: 1,
            label : 'A',
        },
        {
            optionContent: '',
            optionOrder: 2,
            label : 'B',
        },
        {
            optionContent: '',
            optionOrder: 3,
            label : 'C',
        },
        {
            optionContent: '',
            optionOrder: 4,
            label : 'D',
        },
    ];
};

const options = ref<OptionsForm[]>(initOptions());

const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

// 添加选项
const addOption = () => {
    const nextOrder = options.value.length + 1;
    options.value.push({
        optionContent: '',
        optionOrder: nextOrder,
        label: labels[nextOrder - 1] || nextOrder.toString(),
        isCorrect: false
    });
};

// 删除选项
const removeOption = (index: number) => {
    if (options.value.length > 2) {
        options.value.splice(index, 1);
        // 重新排序并更新标签
        options.value.forEach((item, idx) => {
            item.optionOrder = idx + 1;
            item.label = labels[idx] || (idx + 1).toString();
        });
    }
};

// 填空题答案
const fillBlankAnswer = ref('');

// 判断题答案
const trueFalseAnswer = ref(true);

// 单选题正确答案索引
const singleCorrectAnswer = ref<number | null>(null);

// 处理单选题答案变更
const handleSingleAnswerChange = (index: number) => {
    // 重置所有选项的正确状态
    options.value.forEach((item, idx) => {
        item.isCorrect = idx === index;
    });
};

// 题目类型变更处理
const handleTypeChange = (value: string) => {
    if (value === 'single_choice' || value === 'multiple_choice') {
        // 重置选项
        options.value = initOptions();
    } else if (value === 'fill_blank') {
        fillBlankAnswer.value = '';
    } else if (value === 'true_false') {
        trueFalseAnswer.value = true;
    }
};

// 表单提交
const submitForm = () => {
    questionsFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            try {
                // 将图文混排列表转换为JSON字符串
                form.value.title = convertTitleListToJson();

                if (form.value.questionType === 'single_choice' || form.value.questionType === 'multiple_choice') {
                    // 验证是否选择了正确答案
                    const hasCorrect = options.value.some(item => item.isCorrect);
                    if (!hasCorrect) {
                        proxy?.$modal.msgError('请至少选择一个正确答案');
                        buttonLoading.value = false;
                        return;
                    }

                    // 验证选项内容
                    const hasEmpty = options.value.some(item => !item.optionContent);
                    if (hasEmpty) {
                        proxy?.$modal.msgError('选项内容不能为空');
                        buttonLoading.value = false;
                        return;
                    }

                    form.value.answer = options.value.filter(item => item.isCorrect).map(item => item.label).join('');
                    form.value.options = <any> options;

                } else if (form.value.questionType === 'fill_blank') {
                    // 保存填空题答案
                    if (!fillBlankAnswer.value) {
                        proxy?.$modal.msgError('填空题答案不能为空');
                        buttonLoading.value = false;
                        return;
                    }

                    form.value.answer = fillBlankAnswer.value;
                    form.value.options = [];

                } else if (form.value.questionType === 'true_false') {
                    form.value.answer = trueFalseAnswer.value ? '正确' : '错误';
                    form.value.options = [];
                }

                if (form.value.questionId) {
                    // 修改题目
                    await updateQuestions(form.value);
                } else {
                    // 新增题目
                    const res = await addQuestions(form.value);
                }

                proxy?.$modal.msgSuccess(form.value.questionId ? '修改成功' : '添加成功');
                goBack();
            } catch (error) {
                console.error('保存失败', error);
            } finally {
                buttonLoading.value = false;
            }
        }
    });
};

// 返回列表页
const goBack = () => {
    router.push('/answer/questions');
};

// 加载题目详情
const loadQuestionDetail = async (questionId: string | number) => {
    try {
        const res = await getQuestions(questionId);
        if (res.data) {
            // 更新表单数据
            Object.assign(form.value, res.data);
            pageTitle.value = '修改题目';

            // 解析题目内容的JSON字符串为图文混排列表
            if (res.data.title) {
                parseJsonToTitleList(res.data.title);
            }

            if (res.data.questionType === 'single_choice' || res.data.questionType === 'multiple_choice') {

                let arr : OptionsForm[] = [];

                res.data.options.forEach((item, index) => {
                    arr.push({
                        optionContent: item.optionContent,
                        optionOrder: item.optionOrder,
                        label: item.label,
                        isCorrect: res.data.answer.includes(item.label),
                    });
                });

                // 重置选项
                options.value = arr;
                
                // 如果是单选题，初始化正确答案索引
                if (res.data.questionType === 'single_choice') {
                    const correctIndex = options.value.findIndex(item => item.isCorrect);
                    if (correctIndex !== -1) {
                        singleCorrectAnswer.value = correctIndex;
                    }
                }
            } else if (res.data.questionType === 'fill_blank') {
                fillBlankAnswer.value = res.data.answer || '';
            } else if (res.data.questionType === 'true_false') {
                trueFalseAnswer.value = res.data.answer == '正确';
            }

            // 加载选项数据
            // await loadOptions(questionId);
        }
    } catch (error) {
        console.error('获取题目详情失败', error);
        proxy?.$modal.msgError('获取题目详情失败');
    }
};

// // 加载选项数据
// const loadOptions = async (questionId: string | number) => {
//     try {
//         const query: OptionsQuery = { questionId };
//         const res = await listOptions(query);
//         if (res.rows && res.rows.length > 0) {
//             const questionOptions = res.rows;

//             if (form.value.questionType === 'single_choice' || form.value.questionType === 'multiple_choice') {
//                 // 清空默认选项
//                 options.value = [];

//                 // 填充选项数据
//                 questionOptions.forEach((option, index) => {
//                     options.value.push({
//                         optionContent: option.optionContent,
//                         optionOrder: option.optionOrder,
//                         isCorrect: option.isCorrect === 1
//                     });
//                 });
//             } else if (form.value.questionType === 'fill_blank') {
//                 // 填空题只有一个正确答案
//                 const correctOption = questionOptions.find(opt => opt.isCorrect === 1);
//                 if (correctOption) {
//                     fillBlankAnswer.value = correctOption.optionContent;
//                 }
//             } else if (form.value.questionType === 'true_false') {
//                 // 判断题答案
//                 const correctOption = questionOptions.find(opt => opt.isCorrect === 1);
//                 if (correctOption) {
//                     trueFalseAnswer.value = correctOption.optionContent === '正确';
//                 }
//             }
//         }
//     } catch (error) {
//         console.error('获取选项数据失败', error);
//     }
// };

// 在组件挂载时检查是否有questionId参数
onMounted(async () => {
    const questionId = route.query.questionId;
    if (questionId) {
        await loadQuestionDetail(questionId as string);
    }
});
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.option-item {
    margin-bottom: 10px;
}

.option-label {
    display: flex;
    align-items: center;
    justify-content: center;
}

.label-text {
    display: inline-block;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    border-radius: 50%;
    background-color: #409EFF;
    color: white;
    font-weight: bold;
}

/* 内容列表样式 */
.content-list-container {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
    background-color: #f9f9f9;
}

.content-item {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
}

.content-item-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 8px;
    margin-top: 5px; /* 增加顶部间距，与输入框分开 */
    flex-wrap: wrap; /* 允许按钮在需要时换行 */
    min-height: 40px; /* 确保有足够的高度 */
}

.content-actions {
    display: flex;
    gap: 10px;
}

.image-preview {
    margin-bottom: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.preview-image {
    max-width: 100%;
    max-height: 150px;
    object-fit: contain;
}

.no-image {
    color: #909399;
    font-size: 14px;
}
</style>